<?php

namespace App\Console\Commands\Users;

use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AddUserCommand extends Command
{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'users:add
                            {name : The name of the user}
                            {email : The email of the user}
                            {password : The password for the user}';

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = 'Add a new user to the database';

  /**
   * Execute the console command.
   */
  public function handle()
  {
    $name = $this->argument('name');
    $email = $this->argument('email');
    $password = $this->argument('password');

    // Check if user already exists
    if (User::where('email', $email)->exists()) {
      $this->error("A user with email {$email} already exists.");
      return 1;
    }

    try {
      $user = User::create([
        'name' => $name,
        'email' => $email,
        'password' => Hash::make($password),
      ]);

      $this->info("User {$user->name} ({$user->email}) has been added successfully with ID: {$user->id}");
    } catch (\Exception $e) {
      $this->error("Error creating user: " . $e->getMessage());
      return 1;
    }

    return 0;
  }
}
